package com.xwj.redpacket.util;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 二倍均值法计算红包金额
 *
 * @author xwj
 * @date 2020/4/27
 */
public class RedPacketUtil {
    /**
     * @param totalAmount 总金额，单位是分
     * @param totalPeople 总人数
     * @return
     */
    public static List<Integer> divideRedPacket(Integer totalAmount, Integer totalPeople) {
        List<Integer> redPacketList = new ArrayList<>(totalPeople);
        Integer restAmount = totalAmount;
        Integer restPeople = totalPeople;
        Random random = new Random();
        for (int i = 0; i < totalPeople - 1; i++) {
            Integer amount = random.nextInt(restAmount / restPeople * 2 - 1) + 1;
            restAmount = restAmount - amount;
            restPeople--;
            redPacketList.add(amount);
        }
        redPacketList.add(restAmount);
        return redPacketList;
    }

    public static void main(String[] args) {
        List<Integer> redPacketList = divideRedPacket(100, 10);
        Integer sum = 0;
        for(Integer temp : redPacketList) {
            sum += temp;
            System.out.println(new BigDecimal(temp.toString()).divide(new BigDecimal("100")));
        }
        System.out.println(sum);
        System.out.println(redPacketList);
    }
}
